﻿using System.Net;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalExceptionMiddleware> logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="_logger"></param>
        public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> _logger)
        {
            _next = next;
            logger = _logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception exception)
            {
                // 你可以在这里进行相关的日志记录
                await HandleExceptionAsync(context, exception);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            //if (exception.GetType() == typeof(ApplicationException))
            //{
            //    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            //}
            //else if (exception.GetType() == typeof(KeyNotFoundException))
            //{
            //    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            //}
            //else
            //{
            //    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //}
            var responseModel = Models.ApiResponse<string>.Fail(exception.Message);

            logger.LogError(exception, exception.Message);

            await context.Response.WriteAsync(responseModel.ToJsonString());
        }
    }
}
